package com.hddf.project.auth.actions;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.kommii.encryption.AESHandler;
import org.kommii.encryption.MD5Handler;
import org.kommii.log.LogNames;

import com.hddf.project.auth.json_util.JsonProvider;
import com.hddf.project.auth.pojos.User;
import com.hddf.project.auth.service.MongoDB_Query;
import com.hddf.project.auth.service.MongoDB_Sync;
import com.hddf.project.auth.service.RegisterService;
import com.mongodb.DBObject;

public class UserAction extends BaseAction{
	
	private static final long serialVersionUID = 157657542775L;
	private int uid;
	private String user_no;
	private String username;
	private String password ;
	private String department;
	private String description;
    private String mobile_phone;
	private int isopen  ;
	private String permission; 
	private String value;
	private String start;
	private String limit;
	
	@SuppressWarnings("finally")
	public String register(){
		HttpServletRequest request = getRequest();
		Map<String,Object> map = new HashMap<String,Object>();
		String state = "";
		String msg = "";
		try {
			RegisterService rs = RegisterService.getInstance();
			MongoDB_Sync ms = MongoDB_Sync.getInstance();
			MongoDB_Query mq = MongoDB_Query.getInstance();
			User u = new User();
			Date date = new Date();
			
			u.setRegister_date(date);
			u.setLast_login_date(date);
			u.setMobile_phone(mobile_phone);
			u.setDepartment(department);
			u.setDescription(description);
			if(!"all".equals(permission)){
				u.setPermission(permission);
			}
			
			HashMap m = (HashMap)request.getAttribute("user");
			String web_token = (String)m.get("web_token");
			DBObject obj = mq.getSimpleUserByWebToken(web_token);
			String aeskey = (String)obj.get("aes_key");
			value = value.replace(" ", "+");
			String decr_str = AESHandler.decrypt(aeskey, value);
			String[] arr = decr_str.split(" ");
			
			if(arr.length==2){
				username = arr[0];
				password = arr[1];
				u.setUsername(username);
				u.setPassword(password);
				boolean b = rs.addUser(u);
				if(b){
					boolean b2 = ms.addUser(u);
					if(b2){
						state = "ok";
						request.setAttribute("logname",LogNames.user_manager);
						request.setAttribute("logs","add user id: "+u.getId()+" ,add user name: "+username);
					}
				}
			}else{
				state = "error";
				msg = "用户名或密码有误";
			}
		} catch (Exception e) {
			e.printStackTrace();
			state = "error";
			msg = "新增用户异常";
		} finally {
			map.put("state", state);
			map.put("msg", msg);
			request.setAttribute("result", JsonProvider.getCommonJson(map));
			return "simpleResult";
		}
	}
	
	@SuppressWarnings("finally")
	public String getUserList(){
		HttpServletRequest request = getRequest();
		Map<String,Object> map = new HashMap<String,Object>();
		String state = "";
		String msg = "";
		try {
			//RegisterService rs = RegisterService.getInstance();
			MongoDB_Query mq = MongoDB_Query.getInstance();
			HashMap m = (HashMap)request.getAttribute("user");
			String web_token = (String)m.get("web_token");
			List<DBObject> list = mq.getUserList(start,limit,isopen);
			int totalCount = mq.getUserTotalCount(isopen);
			if(null != list){
				state = "ok";
				map.put("user_list", list);
				map.put("totalCount", totalCount);
				request.setAttribute("logname",LogNames.user_select);
				request.setAttribute("logs","select user list: ");
			}else{
				state = "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
			state = "error";
			msg = "查询用户列表异常";
		} finally {
			map.put("state", state);
			map.put("msg", msg);
			request.setAttribute("result", JsonProvider.getJson(map));
			return "simpleResult";
		}
	}
	
	public String delete(){
		HttpServletRequest request = getRequest();
		Map<String,Object> m = new HashMap<String,Object>();
		RegisterService rs = RegisterService.getInstance();
		MongoDB_Sync ms = MongoDB_Sync.getInstance();
		boolean b = false;
		if(0!=uid){
			User u = new User();
			u.setId(uid);
			b = rs.deleteUser(u);
			if(b){
				b = ms.deleteUser(u);
			}
		}
		
		if(b){
			m.put("state", "ok");
			request.setAttribute("logname",LogNames.user_manager);
			request.setAttribute("logs","delete user id: "+uid);
		}else{
			m.put("state", "error");
		}
		request.setAttribute("result", JsonProvider.getCommonJson(m));
		return "simpleResult";
	}
	
	public String setOff(){
		HttpServletRequest request = getRequest();
		Map<String,Object> m = new HashMap<String,Object>();
		RegisterService rs = RegisterService.getInstance();
		MongoDB_Sync ms = MongoDB_Sync.getInstance();
		boolean b = false;
		if(0!=uid){
			User u = new User();
			u.setId(uid);
			b = rs.setUserOff(uid);
			if(b){
				b = ms.setUserOff(uid);
			}
		}
		
		if(b){
			m.put("state", "ok");
			request.setAttribute("logname",LogNames.user_manager);
			request.setAttribute("logs","setOff user  id: "+uid);
		}else{
			m.put("state", "error");
		}
		request.setAttribute("result", JsonProvider.getCommonJson(m));
		return "simpleResult";
	}
	
	public String setOn(){
		HttpServletRequest request = getRequest();
		Map<String,Object> m = new HashMap<String,Object>();
		RegisterService rs = RegisterService.getInstance();
		MongoDB_Sync ms = MongoDB_Sync.getInstance();
		boolean b = false;
		if(0!=uid){
			User u = new User();
			u.setId(uid);
			b = rs.setUserOn(uid);
			if(b){
				b = ms.setUserOn(uid);
			}
		}
		
		if(b){
			m.put("state", "ok");
			request.setAttribute("logname",LogNames.user_manager);
			request.setAttribute("logs","setOn user  id: "+uid);
		}else{
			m.put("state", "error");
		}
		request.setAttribute("result", JsonProvider.getCommonJson(m));
		return "simpleResult";
	}
	
	public String checkUsername(){
		HttpServletRequest request = getRequest();
		Map<String,Object> m = new HashMap<String,Object>();
		RegisterService rs = RegisterService.getInstance();
		MongoDB_Query mq = MongoDB_Query.getInstance();
		boolean b = false;
		if(username!=null && !"".equals(username.trim())){
			User u = mq.getUserByName(username);
			if(null!=u){
				b = true;
			}else{
				b = false;
			}
		}
		
		if(b){
			m.put("state", "ok");
		}else{
			m.put("state", "error");
		}
		request.setAttribute("result", JsonProvider.getCommonJson(m));
		return "simpleResult";
	}
	
	@SuppressWarnings("finally")
	public String getUserById(){
		HttpServletRequest request = getRequest();
		Map<String,Object> map = new HashMap<String,Object>();
		String state = "";
		String msg = "";
		try {
			MongoDB_Query mq = MongoDB_Query.getInstance();
			HashMap m = (HashMap)request.getAttribute("user");
			String web_token = (String)m.get("web_token");
			if(0!=uid && 1!=uid){
				User u = mq.getUserById(uid);
				if(null != u){
					state = "ok";
					map.put("user", u);
					request.setAttribute("logname",LogNames.user_select);
					request.setAttribute("logs","select user  id: "+uid+", select user name: "+u.getUsername());
				}else{
					state = "error";
				}
			}else{
				state = "error";
				msg = "非法id,无法获取用户信息";
			}
		} catch (Exception e) {
			e.printStackTrace();
			state = "error";
			msg = "查询用户异常";
		} finally {
			map.put("state", state);
			map.put("msg", msg);
			request.setAttribute("result", JsonProvider.getJson(map));
			return "simpleResult";
		}
	}
	
	@SuppressWarnings("finally")
	public String updateUserInfo(){
		HttpServletRequest request = getRequest();
		Map<String,Object> map = new HashMap<String,Object>();
		String state = "";
		String msg = "";
		User user = new User();
		try {
			RegisterService rs = RegisterService.getInstance();
			MongoDB_Sync ms = MongoDB_Sync.getInstance();
			MongoDB_Query mq = MongoDB_Query.getInstance();
			boolean result ;
			HashMap m = (HashMap)request.getAttribute("user");
			
			String web_token = (String)m.get("web_token");
			DBObject obj = mq.getSimpleUserByWebToken(web_token);
			String aeskey = (String)obj.get("aes_key");
			//username = (String)obj.get("username");
			boolean b = true; 
			boolean b2 = true;
			if(0!=uid){
				user = mq.getUserById(uid);
				if(null!=user){
					if(!"".equals(username) && null!=username){
						username = username.replace(" ", "+");
						username = AESHandler.decrypt(aeskey, username);
						int len = username.length();
						if(2>len){
							state = "error";
							msg = "用户名长度小于2位,请填写长度大于等于2位的用户名";
							b = false;
						}
						User u = mq.getUserByName(username);
						if(null!=u){
							state = "error";
							msg = "用户 "+username+" 已经存在,请使用其他用户名";
							b = false;
						}
					}else{
						b = false;
					}
					
					if(!"".equals(password) &&  null!=password){
						password = password.replace(" ", "+");
						password = AESHandler.decrypt(aeskey, password);
						int len = password.length();
						if(6>len){
							state = "error";
							msg = "长度小于6位,请填写长度大于等于6位的密码";
							b2 = false;
						}
					}else{
						b2 = false;
					}
				}else{
					state = "error";
					msg = "用户不存在";
				}
			}else{
				state = "error";
				msg = "非法id";
			}
			
			
			if("".equals(state)){
				if(b){
					user.setUsername(username);
				}
				if(b2){
					password = MD5Handler.encrypt(password);
					user.setPassword(password);
				}
				user.setDepartment(department);
				user.setDescription(description);
				user.setMobile_phone(mobile_phone);
				user.setPermission(permission);
				result = rs.updateUser(user);
				if(result){
					result = ms.updateUser(user);
					if(result){
						state = "ok";
						request.setAttribute("logname",LogNames.user_manager);
						request.setAttribute("logs","update userInfo user id: "+uid+
								" ,update userInfo user name:"+user.getUsername());
					}
				}else{
					state = "error";
					msg = "修改用户失败";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			state = "error";
			msg = "修改用户出现异常";
		} finally {
			map.put("state", state);
			map.put("msg", msg);
			request.setAttribute("result", JsonProvider.getCommonJson(map));
			return "simpleResult";
		}
	}
	
	@SuppressWarnings("finally")
	public String updateUserPassword(){
		HttpServletRequest request = getRequest();
		Map<String,Object> map = new HashMap<String,Object>();
		String state = "";
		String msg = "";
		try {
			RegisterService rs = RegisterService.getInstance();
			MongoDB_Sync ms = MongoDB_Sync.getInstance();
			MongoDB_Query mq = MongoDB_Query.getInstance();
			String result = "";
			HashMap m = (HashMap)request.getAttribute("user");
			//JSONObject jobj = JsonProvider.getJsonObject(result);
			String web_token = (String)m.get("web_token");
			DBObject obj = mq.getSimpleUserByWebToken(web_token);
			String aeskey = (String)obj.get("aes_key");
			username = (String)obj.get("username");
			value = value.replace(" ", "+");
			String decr_str = AESHandler.decrypt(aeskey, value);
			String[] arr = decr_str.split(" ");
			String new_pw = "";
			String old_pw = "";
			if(arr.length==2){
				new_pw = arr[1];
				old_pw = arr[0];
			}
			result = rs.updateUserPassword(username, new_pw, old_pw);
			if("1".equals(result)){
				result = ms.updateUserPassword(username, new_pw, old_pw);
				if("1".equals(result)){
					state = "ok";
					request.setAttribute("logname",LogNames.user_manager);
					request.setAttribute("logs","update user password user name: "+username);
				}
			}else{
				state = "error";
				msg = result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			state = "error";
			msg = "修改密码异常";
		} finally {
			map.put("state", state);
			map.put("msg", msg);
			request.setAttribute("result", JsonProvider.getCommonJson(map));
			return "simpleResult";
		}
	}


	public String getUser_no() {
		return user_no;
	}


	public void setUser_no(String user_no) {
		this.user_no = user_no;
	}


	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public String getDepartment() {
		return department;
	}


	public void setDepartment(String department) {
		this.department = department;
	}


	public String getDescription() {
		return description;
	}


	public void setDescription(String description) {
		this.description = description;
	}


	public String getMobile_phone() {
		return mobile_phone;
	}


	public void setMobile_phone(String mobile_phone) {
		this.mobile_phone = mobile_phone;
	}


	public int getIsopen() {
		return isopen;
	}


	public void setIsopen(int isopen) {
		this.isopen = isopen;
	}


	public String getPermission() {
		return permission;
	}


	public void setPermission(String permission) {
		this.permission = permission;
	}


	public String getValue() {
		return value;
	}


	public void setValue(String value) {
		this.value = value;
	}

	public String getStart() {
		return start;
	}

	public void setStart(String start) {
		this.start = start;
	}

	public String getLimit() {
		return limit;
	}

	public void setLimit(String limit) {
		this.limit = limit;
	}

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	

}
